package com.bolang.onlycode.demo.Future;

import java.util.concurrent.*;

public class FutureTaskTest {
    private final  static ConcurrentHashMap<Object,Future<String>> taskCache
            =new ConcurrentHashMap<Object, Future<String>>();
    private static String  executionTask(final String taskName)
        throws ExecutionException,InterruptedException{
        while (true){
             Future<String> future = taskCache.get(taskName);// 1.1 2.1
            if(future==null){
                Callable<String> task =new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return taskName;
                    }
                };
                FutureTask<String> futureTask=new FutureTask<String>(task);
                future = taskCache.putIfAbsent(taskName, futureTask);  // 1.3
                if(future == null){
                    future = futureTask;
                    System.out.println(Thread.currentThread().getName());
                    futureTask.run();            // 1.4 执行任务
                }

            }
            try {
                return future.get();          // 1.5
            }catch (CancellationException e){
                taskCache.remove(taskName,future);
            }
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        executionTask("aa");
    }

}
